<template>
	<view class="tools">
		<tui-card>
			<view class="" slot="body">
				<tui-form ref="uForm" label-width="150">
					<tui-form-item label="上弦文">
						<tui-input :borderBottom="false" v-model="form.sxw" placeholder="请输入上弦文" />
					</tui-form-item>
					<tui-form-item label="下弦文">
						<tui-input :borderBottom="false" v-model="form.xxw" placeholder="请输入下弦文" />
					</tui-form-item>
					<tui-form-item label="印章名称">
						<tui-input :borderBottom="false" v-model="form.yzname" placeholder="请输入印章名称" />
					</tui-form-item>
					<tui-form-item label="大小">
						{{form.size}}
						<tui-slider :width="200" :step="10" :min="300" :value="form.size" @change="sliderchange"
							:max="700" showValue></tui-slider>
					</tui-form-item>
				</tui-form>
				<tui-button @click="submit">生成印章</tui-button>
			</view>
		</tui-card>
		<tui-card>
			<view class="" slot="body">
				<view class="" style="position: relative;width: 100%;display: flex;justify-content: center;">
					<feng-seal :size="form.size+'rpx'" ref="seal" :companyText="form.sxw" :sealCode="form.xxw"
						:sealText="form.yzname"></feng-seal>
				</view>
				<tui-button @click="onsubmit">下载</tui-button>
			</view>
		</tui-card>

	</view>
</template>

<script>
	import fengSeal from "../commponent/feng-seal/components/feng-seal/feng-seal.vue";
	var app = getApp();
	export default {
		data() {
			return {
				form: {
					sxw: '合肥大狗熊股份有限公司',
					xxw: '34014547854545',
					yzname: '小熊专用',
					size: 600,
				},
			};
		},
		components: {
			fengSeal
		},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {

		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {},

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			sliderchange(e) {
				console.log("?????", e.value)
				if (e.value === 300) {
					return
				}
				this.form.size = e.value
			},
			submit() {
				this.$refs.seal.rest()
			},
			onsubmit() {
				this.$refs.seal.make().then((res) => {


					this.saveBase64Image(res.tempFilePath).then(res => {
						console.log(res)
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
					});


				});
			},
			async  saveBase64Image(base64Data, fileName = 'image') {
			  // 处理不同平台的文件后缀
			  const ext = base64Data.startsWith('data:image/') ? 
			             base64Data.split(';')[0].split('/')[1] : 'png';
			  
			  return new Promise((resolve, reject) => {
			    // H5平台处理
			    // #ifdef H5
			    try {
			      // 转换Base64为Blob
			      const byteString = atob(base64Data.split(',')[1] || base64Data);
			      const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
			      const ab = new ArrayBuffer(byteString.length);
			      const ia = new Uint8Array(ab);
			      for (let i = 0; i < byteString.length; i++) {
			        ia[i] = byteString.charCodeAt(i);
			      }
			      const blob = new Blob([ab], { type: mimeString });
			
			      // 创建下载链接
			      const url = window.URL.createObjectURL(blob);
			      const a = document.createElement('a');
			      a.style.display = 'none';
			      a.href = url;
			      a.download = `${fileName}.${ext}`;
			      document.body.appendChild(a);
			      a.click();
			      window.URL.revokeObjectURL(url);
			      document.body.removeChild(a);
			      resolve(url);
			    } catch (error) {
			      reject(new Error('H5保存失败：' + error.message));
			    }
			    // #endif
			
			    // 微信小程序处理
			    // #ifdef MP-WEIXIN
			    const fs = wx.getFileSystemManager();
			    const filePath = `${wx.env.USER_DATA_PATH}/${fileName}.${ext}`;
			
			    // 写入临时文件
			    fs.writeFile({
			      filePath,
			      data: base64Data,
			      encoding: 'base64',
			      success: () => {
			        // 保存到相册
			        wx.saveImageToPhotosAlbum({
			          filePath,
			          success: () => resolve(filePath),
			          fail: (err) => reject(new Error('微信保存失败：' + err.errMsg))
			        });
			      },
			      fail: (err) => reject(new Error('文件写入失败：' + err.errMsg))
			    });
			    // #endif
			
			    // 其他平台处理（如果需要）
			    // #ifndef H5,MP-WEIXIN
			    reject(new Error('暂不支持此平台'));
			    // #endif
			  });
			}
		}
	};
</script>
<style lang="scss" scoped>
	page {
		background-color: #F5F5FA;
	}

	.result {
		padding: 0 4%;
		margin-top: 20upx;
		background-color: #ffffff;
	}

	.result .title {
		padding: 30upx 0 20upx 0;
		font-size: 30upx;
		font-weight: bold;
	}

	.t_input {
		padding: 20upx 4%;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.t_input .title {
		height: 80upx;
		line-height: 80upx;
		color: #333;
		font-weight: bold;
		width: 100upx;
	}

	.t_input .inputs {
		color: #333;
		font-size: 32upx;
	}

	.inputs input {
		height: 80upx;
		line-height: 80upx;
		width: 100%;
		display: block;
	}

	.all_btn {
		font-size: 24upx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		width: 150upx;
	}

	.jilu {
		height: 60upx;
		line-height: 60upx;
		padding: 0 4%;
		font-size: 28upx;
		color: #999;
		font-family: Source Han Sans CN;
		font-weight: 400;
		margin-top: 10upx;
	}

	.addclerk {
		width: 80%;
		height: 82upx;
		line-height: 82upx;
		border-radius: 15upx;
		font-size: 32upx;
		font-family: Source Han Sans CN;
		font-weight: 500;
		color: rgba(255, 255, 255, 1);
		text-align: center;
		position: fixed;
		bottom: 30upx;
		left: 50%;
		transform: translateX(-50%);
		background-color: pink;
	}

	.addclerk:active {
		opacity: 0.8;
	}
</style>
<style>
	page {
		background-color: #F5F5FA;
	}
</style>